﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;
using OfficeOpenXml;
using System.Diagnostics;


namespace DataPie.Core
{
    public class DataTableToExcel
    {


        /// <summary>
        /// 已有工作簿中，添加新的sheet并保存
        /// </summary>
        public static bool SaveExcel(string SheetName, DataTable dt, ExcelPackage package)
        {

            try
            {
                ExcelWorksheet ws = package.Workbook.Worksheets.Add(SheetName);

                ws.Cells["A1"].LoadFromDataTable(dt, true);


                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 保存excel文件，覆盖相同文件名的文件
        /// </summary>
        public static void SaveExcel(string FileName, DataTable dt, string NewSheetName)
        {
            FileInfo newFile = new FileInfo(FileName);
            if (newFile.Exists)
            {
                newFile.Delete();
                newFile = new FileInfo(FileName);
            }
            using (ExcelPackage package = new ExcelPackage(newFile))
            {
                try
                {
                    ExcelWorksheet ws = package.Workbook.Worksheets.Add(NewSheetName);
                    ws.Cells["A1"].LoadFromDataTable(dt, true);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                package.Save();
            }
        }


        /// <summary>
        /// 单表格导出到excel工作簿
        /// </summary>


        /// <summary>
        /// 单表格导出到一个excel工作簿
        /// </summary>







    }
}
